package com.extension.company.common.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Base64;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * 作者:zwk
 * 联系方式：497981239@qq.com
 * 时间：on 2019/7/18 21:01
 * 功能： base64 <--> 图片
 */
public class Base64Utils {

	/**
	 * base64转为bitmap
	 *
	 * @param base64Data 字符串
	 * @return bitmap
	 */
	public static Bitmap base64ToBitmap(String base64Data) {
		byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
		return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
	}


	/**
	 * 将图片转为base64 位
	 *
	 * @param url 图片的地址
	 * @return  string 字符串
	 */
	public static String imgToBase64String(String url) {
		if (url == null) {
			return null;
		}
		Bitmap bitmap = BitmapFactory.decodeFile(url);
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		if (url.indexOf(".") > 0) {
			if (url.contains(".png")) {
				url = url.substring(0, url.indexOf(".png"));
				bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
			} else if (url.contains(".jpg")) {
				url = url.substring(0, url.indexOf(".jpg"));
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
			}
		}

		byte[] byteServer = stream.toByteArray();
		try {
			stream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		String base64String = Base64.encodeToString(byteServer, 0, byteServer.length, Base64.DEFAULT);
		return base64String;
	}


}
